import Vue from 'vue'
import Router from 'vue-router'
import routes from '@/router/routers'
import store from '@/store'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { setTitle } from '@/libs/utils.js'
import { getToken, hasPagePermission } from "@/libs/auth";
Vue.use(Router)

const router = new Router({
    routes
})


const whiteList = ['login', '401', '404', '500'] //免登录白名单中
const LOGIN_PAGE_NAME = 'login'

router.beforeEach((to, from, next) => {
    NProgress.configure({ showSpinner: false });
    //开启NProgress进度条
    NProgress.start()
    //设置浏览器标题
    setTitle(to.meta.title)

    const token = getToken()
    if (!token && to.name !== LOGIN_PAGE_NAME) {
        // 未登录且要跳转的页面不是登录页
        next({
            name: LOGIN_PAGE_NAME // 跳转到登录页
        })
    } else if (!token && to.name === LOGIN_PAGE_NAME) {
        // 未登陆且要跳转的页面是登录页
        next() // 跳转
    } else if (token && to.name === LOGIN_PAGE_NAME) {
        // 已登录且要跳转的页面是登录页
        next({
            name: 'home' // 跳转到home页
        })
    } else {

        //用户刷新了页面，vuex中保存的数据丢失，需重新设置上去，并生成路由表
        if (store.getters.user == null) {
            store.dispatch('SetUserData').then(() => {
                next() // hack方法 确保addRoutes已完成
            })
        } else {
            if (whiteList.indexOf(to.name) !== -1) { //在免登录白名单中，直接进入
                next()
            } else { //验证权限
                if (hasPagePermission(to.meta.auth)) {
                    next()
                } else {
                    next({ replace: true, name: '401' })
                    NProgress.done()
                }
            }
        }
    }
})

router.afterEach(to => {
    NProgress.done() //结束NProgress进度条
})

export default router